package com.sxf.util;

import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;

import org.apache.commons.codec.binary.Base64;

public class PasswordUtils {
	/**
	 * @param msg
	 * @return
	 * @throws Exception
	 */
	public static String md5(String msg) throws Exception {
		String pwd = null;
		if (msg != null && !"".equals(msg.trim())) {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] b = msg.getBytes();
			byte[] b1 = md.digest(b);// 加密
			// 用于把字节数组编码成字符串
			pwd = Base64.encodeBase64String(b1);
		}
		return pwd;
	}

	public static void encodeRandomSalt(String rawPassword) throws Exception {
		byte[] salt = new byte[8];
		SecureRandom random = new SecureRandom();
		random.nextBytes(salt);
		// System.out.println("生成的盐：" + Arrays.toString(salt));

		MessageDigest digest = MessageDigest.getInstance("MD5");// 当然可以使用SHA（160位），MD5(128位)
		digest.update(salt);
		digest.update(rawPassword.getBytes("utf-8"));
		byte[] afterMd5 = digest.digest();
		System.out.println("杂凑值：" + Arrays.toString(afterMd5));

	}

	public static String encode(String rawPassword, String salt)
			throws Exception {
		return encode(null, rawPassword, salt);
	}

	public static String encode(String algorithm, String rawPassword,
			String salt) throws Exception {
		String pwd = null;
		if (algorithm == null || "".equals(algorithm)) {
			algorithm = "MD5";
		}
		if (rawPassword != null && !"".equals(rawPassword)) {

			MessageDigest digest = MessageDigest.getInstance(algorithm);// 当然可以使用SHA（160位），MD5(128位)
			digest.update(salt.getBytes());
			digest.update(rawPassword.getBytes("utf-8"));
			byte[] afterMd5 = digest.digest();
			// System.out.println("杂凑值：" + Arrays.toString(afterMd5));

			// 用于把字节数组编码成字符串

			pwd = Base64.encodeBase64String(afterMd5);
		}
		return pwd;
	}

	public static void main(String[] args) throws Exception {
		System.out.println(encode("iwueriouewroiewu", "weiuriewurioewu"));
		System.out.println(md5("11111"));
	}
}
